#include <Starter.hpp>


int Starter::start(Config &config){

	/* Create and init the HMI */
	Cli cli;
	cli.printWelcome();
	cli.printParameter(config);

	/* Create and init the syntax checker */
	Checker checker;

	/* Create TCP/IP-Client and initiate a new connection */
	TCPClient tcpClient(config.isIPv6Flag());
	TCPConnection *tcpConnection;
	tcpConnection = tcpClient.openConnection(config.getPort(), config.getAddress());

	/* Check if connection was established successfully */
	if(tcpConnection){

		tcpConnection->setSendFlags(MSG_NOSIGNAL);
		tcpConnection->setRecvFlags(MSG_WAITALL);
		cli.printConnectionEstablished();

	}else{

		cli.printConnectionError();
		return CONNECTION_REFUSED;

	}


	while(true){

		std::string inputString;
		std::string outputString;

		/* Print promt and read expression */
		cli.printPrompt();
		cli.readLine(inputString);

		/* Check if the input string is valid and process if neccessary */
		if(checker.validateInput(inputString, outputString)){

			cli.printSend(outputString);

			char rawInput;
			std::string result;
			size_t len = outputString.size()+1;

			/* Transmit the expression */
			tcpConnection->sendData((void*)outputString.c_str(), len);

			/* Receive result from server byte by byte and construct a string*/
			do{

				tcpConnection->receiveData(&rawInput, 1);

				/* Check if an error occured */
				if(tcpConnection->isConnected()){
					result.append(&rawInput,1);
				}else{
					cli.printConnectionError();
					return CONNECTION_BROKEN;
				}

			}while(rawInput != 0);

			/* Print the result */
			cli.printResult(result);


		}else{
			/* Indicate that an format error has occured */
			cli.printFormatError();
		}


	}

	return NO_ERROR;

}

